/**
 * 将传入任意对象的成员变量输出到文件中
 */
package com.baidu.reflectCase;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;

public class MybatisUtil {
    public static void save(Object obj){
        //1.获取对象的class对象
        Class objClass = obj.getClass();

        //2.获取对象的所有成员变量
        Field[] fields = objClass.getDeclaredFields();

        //3.获取对象实际的类名
        String simpleName = objClass.getSimpleName();
        System.out.println("==========================" + simpleName + "==========================");

        //4.创建打印输出流 来写文件
        PrintStream printStream = null;

        try {
            //4.1.给打印流赋值
            printStream = new PrintStream(new FileOutputStream("src/3.txt", true));
            printStream.println("==========================" + simpleName + "==========================");

            //3.遍历成员变量field 并取出值
            for (Field field : fields) {
                //3.1.获取成员变量名
                String name = field.getName();
                //3.2.打开权限
                field.setAccessible(true);
                //3.3.向对象索取值
                Class type = field.getType();
                //3.4.获取对应值
                    String value = field.get(obj) + "";
                    System.out.println(name + " = " + type + " ====> " + value);
                    printStream.println(name + " = " + type + " ====> " + value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != printStream){
                System.out.println("关闭流");
                printStream.close();
            }
        }
    }
}
